package com.hyc.esjd.uitls;

import com.hyc.esjd.pojo.content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtils {
    public static void main(String[] args) throws IOException {
        new HtmlParseUtils().parseJD("算法导论").forEach(System.out::println);
    }

    public List<content> parseJD(String keywords) throws IOException {
        //    https://search.jd.com/Search?keyword=java
        // 前提需要联网
        String url = "https://search.jd.com/Search?keyword=" + keywords + "&enc=utf-8";
        //解析网页(jsoup返回document就是js,浏览器的Document对象)
        Document document = Jsoup.parse(new URL(url), 30000);

        //所有我们再js中可以操作的,在这里都可以
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element.html());
        //获取所有的li标签
        Elements li_elements = document.getElementsByTag("li");
        ArrayList<content> goodsList = new ArrayList<>();
        for (Element el : li_elements) {
            if (el.attr("class").equalsIgnoreCase("gl-item")) {
                String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
                String price = el.getElementsByClass("p-price").eq(0).text();
                String title = el.getElementsByClass("p-name").eq(0).text();
                content content = new content();
                content.setTitle(title);
                content.setImg(img);
                content.setPrice(price);
                goodsList.add(content);
            }
        }
        return goodsList;
    }
}
